import web3, { wallet } from '../index'

// ABI
export const address = import.meta.env.VITE_WEB3_CONTRACTS_DAO_ADDRESS
const abi = [{"inputs":[{"internalType":"contract IERC20","name":"token_","type":"address"}],"stateMutability":"nonpayable","type":"constructor"},{"anonymous":false,"inputs":[{"indexed":false,"internalType":"address","name":"user","type":"address"}],"name":"Buy","type":"event"},{"inputs":[],"name":"buy","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"getAdmin","outputs":[{"internalType":"address","name":"","type":"address"}],"stateMutability":"view","type":"function"},{"inputs":[{"internalType":"uint256","name":"amount","type":"uint256"}],"name":"set","outputs":[],"stateMutability":"nonpayable","type":"function"},{"inputs":[],"name":"token","outputs":[{"internalType":"contract IERC20","name":"","type":"address"}],"stateMutability":"view","type":"function"}]

// 合约
let contract

// 初始化
export function init() {
  if(!contract) {
    contract = new web3.eth.Contract(abi, address, {
      from: wallet.value
    })
  }
  return contract
}

// 开始交易
export function buy() {
  return new Promise((resolve, reject) => {
    init().methods.buy().estimateGas().then(() => {
      init().methods.buy().send()
      .on('receipt', (receipt) => {
        resolve()
      })
      .on('error', (error) => {
        reject()
      })
    }).catch(err => {
      reject(err)
    })
  })
}

export default contract